package cn.lopr.im.api.service.impl;

import cn.lopr.im.api.bean.User;
import cn.lopr.im.api.service.IAuthService;
import cn.lopr.im.api.service.IUserService;
import cn.lopr.im.api.utils.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author shuangyang7
 * @date 2021/5/19 22:15
 */
@Service
public class AuthServiceImpl implements IAuthService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private IUserService userService;

    public boolean refreshToken(String token) throws Exception {
        String cacheToken = redisTemplate.opsForValue().get(token.substring(2));
        if (StringUtils.isEmpty(cacheToken)) {
            throw new Exception("您的登录已经过期，请重新登录");
        }

        try {
            Claims claims = jwtUtil.parseJWT(cacheToken);
            String newToken = jwtUtil.createJWT(claims.getId(), claims.getSubject(), claims.get("role"));
            redisTemplate.opsForValue().set(token, newToken, jwtUtil.getTtl() * 2, TimeUnit.MILLISECONDS);

        } catch (ExpiredJwtException e) {
            throw new Exception("您的登录已经过期，请重新登录");
        }

        return true;
    }

    public User getInfoByToken(String token) {

        String cacheToken = redisTemplate.opsForValue().get(token.substring(2));

        Claims claims = jwtUtil.parseJWT(cacheToken);
        return userService.getUserById(Integer.parseInt(claims.getId()));
    }

    public String addCache(User res) {
        String token = jwtUtil.createJWT(res.getId() + "", res.getPhone(), "user");

        redisTemplate.opsForValue().set(token, token, (jwtUtil.getTtl()) * 2, TimeUnit.MILLISECONDS);
        return token;
    }
}
